import { _ as _async_to_generator } from "@swc/helpers/_/_async_to_generator";
import { _ as _ts_generator } from "@swc/helpers/_/_ts_generator";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
import IsBetween from "dayjs/plugin/isBetween";
import IsSameOrAfter from "dayjs/plugin/isSameOrAfter";
import React from "react";
import { BSC, ETHEREUM, CONFLUX, TEST_CHAIN, isDomesticVersion, switchDomesticVersion } from "../config";
import { KEYCONST } from "../enums";
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(IsBetween);
dayjs.extend(IsSameOrAfter);
dayjs.tz.setDefault("Asia/Shanghai");
/**
/**
 * @param dayjs
 * @param wait
 */ export function debounceFn(fn) {
    var delay = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 300;
    var _this = this;
    var timer = null;
    return function() {
        for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
            args[_key] = arguments[_key];
        }
        return new Promise(function(resolve) {
            clearTimeout(timer);
            timer = setTimeout(function() {
                fn.apply(_this, args);
            }, delay);
        });
    };
}
/**
 ** 判断是否是有刘海屏的iPhone
 *
 * @export
 * @param {string} info 设备型号信息，Taro.getSystemInfoSync() | DeviceInfo.getDeviceId()(react-native-device-info库)
 * @returns
 */ export function judgmentNewPhone() {
    var device = navigator.userAgent;
    var isNewPhone = !!device.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    return isNewPhone;
}
/** 解析时间字符串 */ export var formatDateStr = function(str) {
    var DMap = {
        January: "01",
        february: "02",
        March: "03",
        April: "04",
        May: "05",
        June: "06",
        July: "07",
        August: "08",
        September: "09",
        October: "10",
        November: "11",
        December: "12"
    };
    var reg = /(\w+) (\d+) at (\d{2}:\d{2}) ([A-Z]{3})/;
    var match = Array.from(str.match(reg));
    var dateStr = "2022 ".concat(DMap[match === null || match === void 0 ? void 0 : match[1]], "-").concat(match === null || match === void 0 ? void 0 : match[2], " ").concat(match === null || match === void 0 ? void 0 : match[3]);
    return dayjs(dateStr).utc().format("MM-DD HH:mm ETC");
};
export var formateDate = function(dateStr) {
    var information = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "YYYY-MM-DD HH:mm:ss UTC+8";
    try {
        return dayjs(dateStr).tz()// .utc()
        // .tz(dayjs.tz.guess())
        .format(information);
    } catch (e) {
        return "";
    }
};
/** wallet的跟节点 只能在组件中使用 */ export var walletRootRef = /*#__PURE__*/ React.createRef();
/** 加载js文件 */ export function loadJS(url, callback) {
    var script = document.createElement("script"), fn = callback || function() {};
    script.type = "text/javascript";
    //IE
    script.onload = function() {
        fn();
    };
    script.onerror = function() {
        script.remove();
    };
    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}
/** 获取图片地址 */ export var matchTheme = function() {
    var theme = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "light", map = arguments.length > 1 ? arguments[1] : void 0;
    return map[theme] || Object.values(map)[0];
};
/** 匹配数字 */ export var matchNumber = function(val) {
    var reg = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;
    return reg.test(val);
};
function trimExtraChar(value, char, regExp) {
    var index = value.indexOf(char);
    if (index === -1) {
        return value;
    }
    if (char === "-" && index !== 0) {
        return value.slice(0, index);
    }
    return value.slice(0, index + 1) + value.slice(index).replace(regExp, "");
}
/** 格式化数字 */ export var formatNumber = function(val) {
    var allowDot = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true, allowMinus = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : true;
    var value = val;
    if (allowDot) {
        value = trimExtraChar(value, ".", /\./g);
    } else {
        value = value.split(".")[0];
    }
    if (allowMinus) {
        value = trimExtraChar(value, "-", /-/g);
    } else {
        value = value.replace(/-/, "");
    }
    var regExp = allowDot ? /[^-0-9.]/g : /[^-0-9]/g;
    return value.replace(regExp, "");
};
export var isMobile = function() {
    var flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
    return flag;
};
export var getSpec = function(chainType, spec) {
    var chainName = getChainName(chainType);
    if (chainName) {
        var map = {
            BSC: {
                ERC20: "BEP-20",
                ERC721: "ERC-721",
                "ERC-20": "BEP-20",
                "ERC-721": "ERC-721",
                native: "BEP-20"
            },
            CONFLUX: {
                ERC20: "CRC-20",
                ERC721: "CRC-721",
                "ERC-20": "CRC-20",
                "ERC-721": "CRC-721",
                native: "CRC-20"
            },
            ETHEREUM: {
                ERC20: "ERC-20",
                ERC721: "ERC-721",
                "ERC-20": "ERC-20",
                "ERC-721": "ERC-721",
                native: "ERC-20"
            }
        };
        return (map[chainName] || {})[spec] || spec;
    }
    return spec;
};
/** （主要用来获取不同链的icon） */ export var getMapFinalValue = function(keys, map) {
    var finalVal = "";
    keys.forEach(function(key) {
        finalVal = map[key];
    });
    return finalVal || "";
};
/** 获取链类型 */ export var getChainName = function(chainType) {
    var map = {
        BSC: BSC,
        ETHEREUM: ETHEREUM,
        CONFLUX: CONFLUX
    };
    var chainKey = Object.keys(map).find(function(key) {
        return map[key].includes(chainType);
    });
    return chainKey;
};
/** 获取不同链的区块链浏览器 */ export var getChainBrowser = function(chainType, txHash) {
    var map = {
        BSC: {
            test: "https://testnet.bscscan.com/tx/",
            main: "https://bscscan.com/tx/"
        },
        ETHEREUM: {
            test: "https://goerli.etherscan.io/tx/",
            main: "https://etherscan.io/tx/"
        },
        CONFLUX: {
            test: "https://testnet.confluxscan.io/transaction/",
            main: "https://www.confluxscan.io/transaction/"
        }
    };
    var key = getChainName(chainType);
    return "".concat(map[key]["".concat(TEST_CHAIN.includes(chainType) ? "test" : "main")]).concat(txHash);
};
/** 获取不同链的区块链浏览器 */ export var getNFTBrowser = function(chainType, contractAddress, tokenID) {
    var map = {
        BSC: {
            test: "https://testnet.bscscan.com/nft/",
            main: "https://bscscan.com/nft/"
        },
        ETHEREUM: {
            test: "https://goerli.etherscan.io/nft/",
            main: "https://etherscan.io/nft/"
        },
        CONFLUX: {
            test: "https://testnet.confluxscan.io/nft/cfx:",
            main: "https://www.confluxscan.io/nft/cfx:"
        }
    };
    var key = getChainName(chainType);
    return "".concat(map[key]["".concat(TEST_CHAIN.includes(chainType) ? "test" : "main")]).concat(contractAddress, "/").concat(tokenID);
};
/** 切换版本 */ export var switchVersion = function(domestic) {
    if (domestic === isDomesticVersion) return;
    switchDomesticVersion(domestic);
    localStorage.setItem(KEYCONST.domestic, JSON.stringify(domestic));
    location.reload();
};
/** 一些操作比较时间的方法 */ export var dateCompare = {
    /** 是否在其他两个时间之间 */ isBetween: function(currentTime, startTime, endTime, option, d) {
        return dayjs(currentTime).tz().isBetween(startTime, endTime, option, d);
    },
    /** 是否相同或之后 */ isSameOrAfter: function(current, date, unit) {
        return dayjs(current).isSameOrAfter(date, unit);
    },
    /** 是否之后 */ isAfter: function(current, date, unit) {
        return dayjs(current).tz().isAfter(date, unit);
    },
    /** 是否之前 */ // isBefore: (a: string, b: string, unit: dayjs.UnitType) =>
    //   dayjs(a).isBefore(b, unit),
    isBefore: function(current, date, unit) {
        return dayjs(current).tz().isBefore(date, unit);
    }
};
var getFileExt = function(url) {
    var index = url.lastIndexOf(".");
    return url.substring(index + 1);
};
/** 只允许下载同源和跨域文件 */ export var downloadFile = function(url, fileName) {
    // let a = document.createElement('a');
    // a.download = `${fileName}.png`;
    // a.href = url;
    // // a.style.display = 'none';
    // document.body.appendChild(a)
    // a.click();
    // window.URL.revokeObjectURL(url);
    // a.remove();
    return fetch(url, {
        method: "get",
        referrerPolicy: "no-referrer"
    }).then(function(res) {
        return res.blob();
    }).then(function(res) {
        var aElement = document.createElement("a");
        aElement.setAttribute("download", "".concat(fileName, ".").concat(getFileExt(url)));
        var href = URL.createObjectURL(res);
        console.log(href);
        aElement.href = href;
        aElement.setAttribute("target", "_blank");
        aElement.click();
        URL.revokeObjectURL(href);
    });
};
export var downloadImg = function(url, fileName, qrCode, onerror) {
    var image = new Image();
    image.crossOrigin = "anonymous";
    image.onerror = function(e) {
        // console.log(e,'a')
        onerror(e);
        throw "load img error";
    };
    image.onload = /*#__PURE__*/ _async_to_generator(function() {
        var canvas, context, blobUrl, a;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    canvas = document.createElement("canvas");
                    canvas.width = image.width;
                    canvas.height = image.height;
                    context = canvas.getContext("2d");
                    context.drawImage(image, 0, 0, image.width, image.height);
                    if (!qrCode) return [
                        3,
                        2
                    ];
                    return [
                        4,
                        drawQR(context)
                    ];
                case 1:
                    _state.sent();
                    _state.label = 2;
                case 2:
                    blobUrl = canvas.toDataURL("image/".concat(getFileExt(url)));
                    a = document.createElement("a");
                    a.download = "".concat(fileName, ".").concat(getFileExt(url));
                    a.href = blobUrl;
                    a.click();
                    canvas = null;
                    window.URL.revokeObjectURL(blobUrl);
                    return [
                        2
                    ];
            }
        });
    });
    var drawQR = function(context) {
        if (!qrCode.url) return false;
        return new Promise(function(resolve) {
            if (typeof qrCode.url == "string") {
                var qrImage = new Image();
                image.crossOrigin = "anonymous";
                qrImage.onload = function() {
                    var _qrCode_width;
                    var width = (_qrCode_width = qrCode.width) !== null && _qrCode_width !== void 0 ? _qrCode_width : image.width / 4;
                    var height = width;
                    var _qrCode_x;
                    var x = (_qrCode_x = qrCode.x) !== null && _qrCode_x !== void 0 ? _qrCode_x : image.width - width - image.width / 10;
                    var _qrCode_y;
                    var y = (_qrCode_y = qrCode.y) !== null && _qrCode_y !== void 0 ? _qrCode_y : image.height - width - image.height / 10;
                    context.drawImage(qrImage, x, y, width, height);
                    resolve(true);
                };
                qrImage.src = qrCode.url;
            } else {
                var _qrCode_width;
                var width = (_qrCode_width = qrCode.width) !== null && _qrCode_width !== void 0 ? _qrCode_width : image.width / 4;
                var height = width;
                var _qrCode_x;
                var x = (_qrCode_x = qrCode.x) !== null && _qrCode_x !== void 0 ? _qrCode_x : image.width - width - image.width / 10;
                var _qrCode_y;
                var y = (_qrCode_y = qrCode.y) !== null && _qrCode_y !== void 0 ? _qrCode_y : image.height - width - image.height / 10;
                if (qrCode.type === "svg") {
                    var svgPath = qrCode.url.querySelectorAll("path")[1];
                    var bbox = svgPath.getBBox();
                    var style = getComputedStyle(svgPath);
                    var path = new Path2D(svgPath.getAttribute("d"));
                    var fillStyle = style.fill;
                    context.save();
                    context.translate(x, y);
                    context.scale(width / bbox.width, height / bbox.height);
                    context.fillStyle = fillStyle;
                    context.fill(path, "evenodd");
                    context.restore();
                    resolve(true);
                } else {
                    context.drawImage(qrCode.url, x, y, width, height);
                    console.log("svg");
                    resolve(true);
                }
            }
        });
    };
    // image.src =
    //   'https://cn.bing.com/th?id=OVFT.RAIsumJyGJlIopO8594wMi&pid=News&w=1200&h=800&c=14&rs=2&qlt=90';
    image.src = url;
};

 //# sourceMappingURL=index.js.map